<template>
    <el-container>
        <el-main class="wrapper">
            <v-breadcrumb v-bind:breadcumb="breadcumb"></v-breadcrumb>
            <section class="panel" :style="{height: mainHeight+'px'}">
                <el-container style="margin-top:15px;">
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                        <el-form-item required label="分享展示图" prop="share_img">
                            <el-row :gutter="20">
                                <el-col :span="4" style="text-align: left">
                                    <label class="btn btn-label" for="uploads">上传</label>
                                    <input type="file" id="uploads" style="clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event, 1)">
                                    <label class="btn btn-label" @click="rotateLeft">旋转</label>
                                    <label class="btn btn-label" @click="finish('blob')">确定</label>
                                </el-col>
                                <el-col :span="18">
                                    <div class="show-preview" :style="{'border': '1px dashed #ccc','width': '360px', 'height': '204px',  'overflow': 'hidden', 'margin': '5px', 'margin-left': '68px'}">
                                        <div :style="previews.div" class="preview">
                                            <img :src="previews.url" :style="previews.img">
                                        </div>
                                    </div>
                                </el-col>
                                <el-col :span="24">
                                    <div style="width: 100%;height: 255px;border: 1px dashed #ccc;margin-top: 5px">
                                        <vueCropper
                                            ref="cropper"
                                            :img="ruleForm.share_img"
                                            :outputSize="option.size"
                                            :outputType="option.outputType"
                                            :info="true"
                                            :full="option.full"
                                            :canMove="option.canMove"
                                            :autoCrop="option.autoCrop"
                                            :autoCropWidth="option.autoCropWidth"
                                            :autoCropHeight="option.autoCropHeight"
                                            :canMoveBox="option.canMoveBox"
                                            :fixedBox="option.fixedBox"
                                            :original="option.original"
                                            @realTime="realTime">
                                        </vueCropper>
                                    </div>
                                </el-col>
                            </el-row>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitForm('ruleForm')">更新保存</el-button>
                            <el-button @click="resetForm('ruleForm')">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-container>
            </section>
        </el-main>
    </el-container>
</template>
<script>
    import {mapGetters} from 'vuex';
    import vBreadcrumb from '../layout/breadcrumb.vue';
    import {ConfigALL,ConfigUpdate} from '../../utils/axios';
    import { VueCropper }  from 'vue-cropper';
    export default {
        components:{vBreadcrumb,VueCropper},
        data(){
            return {
                breadcumb:[{name: "配置管理"}],
                updateDialogTile:'',

                previews: {},
                option: {
                    size: 1,
                    full: false,
                    outputType: 'png',
                    canMove: true,
                    fixedBox: true,
                    autoCrop: true,
                    autoCropWidth: 360,
                    autoCropHeight: 204,
                    original: false,
                    canMoveBox: true
                },
                //用户表单
                ruleForm: {
                    share_img: '',
                },
                rules: {
                    share_img: [{ required: true, message: '请填写分享封面图链接地址', trigger: 'blur' }],
                }

            }
        },
        activated(){
            this.$store.dispatch('setActive', '/cofing');
            this.getAll();
            this.previews =  {};
        },
        computed: {
            ...mapGetters(['active','mainHeight','loading','upload']),
            myHeaders(){
                var token = this.$storage.get('token');
                return {
                    Authorization:token.token_type+' ' + token.access_token,
                    Accept:'application/json'
                }
            },
        },
        methods:{
            //获取配置信息
            getAll(){
                this.$store.dispatch('setLoading', true);
                ConfigALL().then((response)=>{
                    if (response.code) {
                        this.$message.error(response.msg);
                    } else {
                        this.$store.dispatch('setLoading', false);
                        this.ruleForm = response.data;
                    }
                })
            },
            //重置表单
            resetForm(formName) {
                if (this.$refs[formName]!==undefined) {
                    this.$refs[formName].resetFields();
                }
            },
            realTime (data) {
                this.previews = data
            },
            rotateLeft() {
                this.$refs.cropper.rotateLeft();
            },
            uploadImg (e) {
                var file = e.target.files[0];
                if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(e.target.value)) {
                    this.$message.error('图片类型必须是.gif,jpeg,jpg,png中的一种');
                    return false;
                }
                var reader = new FileReader();
                reader.onload = (e) => {
                    let data;
                    if (typeof e.target.result === 'object') {
                        // 把Array Buffer转化为blob 如果是base64不需要
                        data = window.URL.createObjectURL(new Blob([e.target.result]))
                    } else {
                        data = e.target.result;
                    }
                    this.ruleForm.share_img = data;
                }
                // 转化为blob
                reader.readAsArrayBuffer(file);
            },
            finish(){
                let formData = new FormData();
                this.$refs.cropper.getCropBlob((data) => {
                    let token = this.$storage.get('token');
                    formData.append("pic", data, this.ruleForm.share_img);
                    this.$axios.post(this.upload, formData, {
                        headers:{
                            'Authorization':token.token_type+' ' + token.access_token,
                            'Accept':'application/json'
                        }
                    }).then((response)=>{
                        this.ruleForm.share_img = response.data.data.path;
                    });
                })
            },
            submitForm(formName){
                if(this.ruleForm.share_img.indexOf('blob:') != -1){
                    this.$message.error('请确定上传分享展示的裁剪图片');
                    return false;
                }
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        ConfigUpdate(this.ruleForm).then((response)=>{
                            if(response.code){
                                this.$message.error(response.msg);
                            }else{
                                this.$message({
                                    type: 'success',
                                    duration: '1000',
                                    message: response.msg,
                                    onClose:() =>{
                                        this.updateDialog = false;
                                        this.getAll();
                                    }
                                });
                            }
                        });
                    }
                });
            }

        },
        filters: {
            channel: function (val,data) {
                if (!val) return '';
                let name = '';
                data.filter((item)=>{
                    if(item.id === val){
                        name = item.name;
                    }
                });
                return name;
            }
        }
    }
</script>
